import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';

import {
    LoginWrapper,
    LoginBox,
    Input,
    Button
} from './style';

import { actionCreators } from './store';

class Login extends PureComponent {
    render() {
        const {username, password, isLogin, handleInputUsername, handleInputPassword, handleLogin} = this.props;
        if (!isLogin) {
            return (
                <LoginWrapper>
                    <LoginBox>
                        <Input placeholder="账号" type="text" onChange={handleInputUsername} value={username}/>
                        <Input placeholder="密码" type="password" onChange={handleInputPassword} value={password}/>
                        <Button onClick={() => handleLogin(username, password)}>登录</Button>
                    </LoginBox>
                </LoginWrapper>
            );
        } else {
            return <Redirect to="/" />;
        }
    }
}

const mapStateToProps = (state) => ({
    username: state.getIn(["login", "username"]),
    password: state.getIn(["login", "password"]),
    isLogin: state.getIn(["login", "isLogin"])
});

const mapDispatchToProps = (dispatch) => ({
    handleLogin(username, password) {
        dispatch(actionCreators.login(username, password));
    },
    handleInputUsername(e) {
        dispatch(actionCreators.changeUsername(e.target.value));
    },
    handleInputPassword(e) {
        dispatch(actionCreators.changePassword(e.target.value));
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(Login);